package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author zhangbaiyan
 * @date 2024-10-02 19:34
 * @description:
 * @version:
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
     private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.itheima.anno.Log)")
    private void pointCut() {}

    @Around("pointCut()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人ID -当前员工ID
        //获取请求头中的jwt令牌,解析令牌
        String jwt = request.getHeader("token");
        System.out.println("jwt:"+jwt +";");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //方法返回值
        String returnObject = JSONObject.toJSONString(result);

        //操作耗时
        long costTime = end - begin;

        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnObject,costTime);
        operateLogMapper.insert(operateLog);
        log.info("操作日志记录:{}",operateLog);
        return result;
    }
}
